#!/bin/bash

# 检查参数数量
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 {test|pro}"
    exit 1
fi

# 获取参数
ENV=$1
# 初始化变量
HOST="ecs2.zhangjianyong.top"
REMOTE_PATH=""
REMOTE_JAR=""
LOCAL_JAR="blog-main/target/blog-main-0.0.1-SNAPSHOT.jar"
# 根据参数执行不同的操作
case $ENV in
    test)
        echo "Deploying to test environment..."
        REMOTE_PATH=/root/blog-test-api
        REMOTE_JAR=$REMOTE_PATH/blog-api-test.jar
        HOST="ecs2.zhangjianyong.top"
        ;;
    pro)
        echo "Deploying to production environment..."
        REMOTE_PATH=/root/blog-api
        REMOTE_JAR="$REMOTE_PATH/blog-api-0.0.1-SNAPSHOT.jar"
        HOST="ecs1.zhangjianyong.top"
        ;;
    *)
        echo "Invalid argument. Usage: $0 {test|pro}"
        exit 1
        ;;
esac


# 构建项目
#jenv local 17 && mvn clean package -pl blog-main -am -DskipTests
jenv local 17 && mvn clean package -DskipTests
if [ $? -ne 0 ]; then
    echo "Maven build failed."
    exit 1
fi
# 打印变量
echo "Local JAR: $LOCAL_JAR"
echo "Remote JAR: $REMOTE_JAR"
#  复制JAR文件
scp $LOCAL_JAR root@$HOST:$REMOTE_JAR
if [ $? -ne 0 ]; then
    echo "SCP failed."
    exit 1
fi

sleep 3
#  远程执行命令
ssh root@$HOST "sh $REMOTE_PATH/restart.sh"
if [ $? -ne 0 ]; then
    echo "SSH command failed."
    exit 1
fi